package com.dog.basics.api.controller.common;


import cn.hutool.core.lang.Validator;
import com.dog.basics.common.constant.SwaggerConstants;
import com.dog.basics.common.photooss.service.PhotoOssUtil;
import com.dog.basics.common.properties.FileProperties;
import com.dog.basics.common.util.FileNameUtils;
import com.dog.basics.common.util.FileUtils;
import com.dog.basics.common.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传 controller
 *
 * @author dog
 */
@RestController
@RequestMapping("/api/file")
@AllArgsConstructor
@Api(value = "upload", tags = SwaggerConstants.API_ALL)
@Log4j2
public class FileController {

    private final FileProperties fileProperties;
    private final PhotoOssUtil photoOssUtil;

    /**
     * @Description:  上传图片(服务器)
     * @Param:   file
     * @return:  String
     * @Author: wph
     * @Date: 2020/3/27 0027
     */
/*    @ApiOperation(value = "上传图片(服务器)", notes = "上传图片(服务器)", tags = SwaggerConstants.API_UPLOD)
    @PostMapping("/upload/element")
    public R<String> uploadElementFile(@RequestParam("file") MultipartFile file) {
        //  判断图片
        if (!file.isEmpty()) {
            try {
                return R.ok(photoOssUtil.uploadFile(file, null, null, null));
            } catch (Exception e) {
                log.error("上传失败文件:" + e.getMessage());
            }
        }
        return R.failed("上传失败");
    }
*/
    @PostMapping("/upload/file")
    @ApiOperation(value = "上传图片(非服务器)", notes = "上传图片(非服务器)", tags = SwaggerConstants.API_UPLOD)
    public R<String> upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return R.failed();
        }
        String fileName = FileNameUtils.getFileName(FileNameUtils.getSuffix(file.getOriginalFilename()));
        //判断上传是否成功
        if (Validator.isFalse(FileUtils.upload(file, fileProperties.url(), fileName))) {
            return R.failed("上传失败");
        }
        return R.ok(fileName);
    }


    }


